import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'

// 路由配置
const routes = [
  {
    path: '/',
    children: [
      {
        path: '/chat',
        name: "AI-Talk",
        component: () => import('@/views/AiTalk.vue'),
        meta: {
          title: 'AI对话',
          requiresAuth: true
        }
      },
      {
        path: '/',
        name: "AI-Paint",
        component: () => import('@/views/AiPaint.vue'),
        meta: {
          title: 'AI绘画',
          requiresAuth: true,
          KeepAlive: true,
        }
      },
      {
        path: "/draw/convert",
        name: "ImageConversion",
        component: () => import('@/views/ImageConversion.vue'),
        meta: {
          title: '图像转换',
          requiresAuth: true,
        },
      },
      {
        path: '/user/profile',
        name: 'UserProfile',
        component: () => import('@/views/user/UserProfile.vue'),
        meta: {
          title: '个人中心',
          requiresAuth: true
        }
      },
      {
        path: '/draw/history',
        name: 'UserHistory',
        component: () => import('@/views/user/AiPaintHistory.vue'),
        meta: {
          title: '历史记录',
          requiresAuth: true,
          KeepAlive: true,
        }
      },
      {
        path: '/admin',
        name: 'Admin',
        component: () => import('@/views/admin/UserManagement.vue'),
        meta: {
          title: '管理员',
          // requiresAuth: true,
          // roles:['admin']
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login', 
    component: () => import('@/views/user/UserLogin.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/user/UserRegister.vue'),
  },
  {
    path: '/admin/login',
    component: () => import('@/views/admin/AdminLogin.vue'),
    meta: { requiresAuth: false }
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 玲珑AI` : '玲珑AI'
  
  if (to.meta.requiresAuth) {
    if (!userStore.token) {
      next('/login')
      return
    }
    
    // 检查权限
    if (to.meta.roles && !to.meta.roles.includes(permissionStore.role)) {
      next('/403')
      return
    }
  }
  next()
})

export default router
